//
//  GoodDetailViewController.m
//  OrderMeal
//
//  Created by 宏创 on 14-3-7.
//  Copyright (c) 2014年 周浩. All rights reserved.
//

#import "GoodDetailViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "MemberOrderController.h"
#import "NonMemberOrderController.h"
#import "shoppingCartCell.h"
#import "UIView+Toast.h"
@interface GoodDetailViewController ()<UITextFieldDelegate>
{
    NSString *_memberID;
    NSInteger _quantity;
    NSString *returnGoodsId;
}

@end

@implementation GoodDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"goodsid--->%@",self.goodsid);
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    _memberID=[defaults objectForKey:@"memberID"];
    _quantity=[self.quantityField.text intValue];
    
    if (_quantity==1) {
       self.minus.enabled=NO;
    }
    
    [self.plusBtn.layer setBorderWidth:1.0];
    [self.plusBtn.layer setBorderColor:[[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0]CGColor]];
    [self.minusBtn.layer setBorderWidth:1.0];
    [self.minusBtn.layer setBorderColor:[[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0]CGColor]];
    [self.buyBtn.layer setCornerRadius:8.0];
    [self.joinBtn.layer setCornerRadius:8.0];
    
    self.inventory.text = [NSString stringWithFormat:@"库存%@",self.limitNum];
    self.goodPrice.text = [NSString stringWithFormat:@"¥%@",self.goodInfo[@"price"]];
    self.goodMsg.text = self.goodInfo[@"description"];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"会员立即购买"]) {
        MemberOrderController *memberOrder = segue.destinationViewController;
        memberOrder.selectedGoods = [[NSMutableArray alloc]initWithObjects:@{
                                                                    @"goodsName":self.goodInfo[@"name"],
                                        @"goodsPrice":[NSString stringWithFormat:@"%@",self.goodInfo[@"price"]],
                                                                    @"goodsQuantity":self.quantityField.text
                                                                      }, nil];
        memberOrder.goodsids = [[NSMutableArray alloc]init];
        [memberOrder.goodsids addObject:self.goodsid];
        int num = [self.quantityField.text intValue];
        float price = [(NSString *)self.goodInfo[@"price"] floatValue];
        memberOrder.totalPrice = [NSString stringWithFormat:@"￥%.2f",num*price];
    }else{
        NonMemberOrderController *noMemberOrder=segue.destinationViewController;
        noMemberOrder.goodsid = [[NSMutableArray alloc]init];
        noMemberOrder.goodsNum = [[NSMutableArray alloc]init];
        [noMemberOrder.goodsid addObject:self.goodsid];
        [noMemberOrder.goodsNum addObject:[NSString stringWithFormat:@"%d",_quantity]];
    }
}

-(void)requestWithMemberID:(NSString *)memberId
                   goodsID:(NSString *)goodsid
                  quantity:(NSString *)quantity
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    NSDictionary *parameters=@{
                               @"memberId" : memberId,
                               @"goodsid"  : goodsid,
                               @"quantity" : quantity
                               };
    [manager GET:cartadd_url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *status=responseObject[@"success"];
        if ([status isEqualToNumber:@1]) {
            NSLog(@"加入购物车成功");
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"添加购物车成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            }else{
             NSLog(@"--%@",responseObject[@"msg"]);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
    }];
}

- (IBAction)addShoppingCard:(UIButton *)sender{
    if ([self checkInput]) {
        if (_memberID) {
            [self requestWithMemberID:_memberID
                              goodsID:_goodsid
                             quantity:self.quantityField.text];
        }else{
            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"NonMemberShoppingCart-Info" ofType:@"plist"];
            NSMutableArray *arrayData = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
            [arrayData addObject:@{@"goodsInfo": self.goodInfo[@"name"],
                                   @"goodsPrice":[NSString stringWithFormat:@"%@",self.goodInfo[@"price"] ],
                                   @"goodsQuantity":[NSString stringWithFormat:@"%@",self.quantityField.text],
                                   @"goodsRemain":[NSString stringWithFormat:@"%@",self.limitNum],
                                   @"goodsid":self.goodsid}];
            [arrayData writeToFile:plistPath atomically:YES];
            [self.view makeToast:@"加入购物车成功" duration:2.0 position:@"center"];
        }
    }
}

- (IBAction)buy:(UIButton *)sender {
    if ([self checkInput]) {
        NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
        NSString *memberID=[userDefaults objectForKey:@"memberID"];
        if (memberID!=NULL) {
            [self addShoppingCartWithMemberID:_memberID goodsID:self.goodsid quantity:self.quantityField.text];
        }else{
            [self performSegueWithIdentifier:@"非会员订餐" sender:_goodsid];
        }

    }
}

- (IBAction)minus:(UIButton *)sender {
    self.quantityField.text=[NSString stringWithFormat:@"%d",--_quantity];
    if(_quantity==1){
        self.minus.enabled=NO;
    }
}

- (IBAction)add:(UIButton *)sender {
    self.quantityField.text=[NSString stringWithFormat:@"%d",++_quantity];
    if (_quantity>1) {
        self.minus.enabled=YES;
    }
}


-(void)addShoppingCartWithMemberID:(NSString *)memberId
                   goodsID:(NSString *)goodsid
                  quantity:(NSString *)quantity
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    NSDictionary *parameters=@{
                               @"memberId" : memberId,
                               @"goodsid"  : goodsid,
                               @"quantity" : quantity
                               };
    [manager GET:cartadd_url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *status=responseObject[@"success"];
        if ([status isEqualToNumber:@1]) {
            [self performSegueWithIdentifier:@"会员立即购买" sender:nil];
        }else{
            UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"消息" message:@"购买失败" delegate:self cancelButtonTitle:@"确认[" otherButtonTitles:nil, nil];
            [alert show];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"消息" message:@"购买失败" delegate:self cancelButtonTitle:@"确认[" otherButtonTitles:nil, nil];
        [alert show];
    }];
}

-(BOOL)checkInput{
    if ([self.quantityField.text intValue]>[self.limitNum intValue]) {
        NSLog(@"quantity--->%@",self.quantityField.text);
        NSLog(@"inventory--->%@",self.inventory.text);
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:@"超出库存了,请修改商品数量" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else{
        return YES;
    }
}
@end
